// pages/mall/mall.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navTab: ["主页", "分类", "购物车"],
    currentNavtab: "0",
    indicatorDots: false,
    autoplay: true,
    interval: 5000,
    duration: 1000,

    // 分类
    hidden:false,
		curNav:1,
		curIndex:1,
		cart:[],
		cartTotal:0,
		// 侧边栏名称
		navList:[
			{
				id:0,
				name:'全部'
			},
			{
				id:1,
				name:'C/C++'
			},
			{
				id:2,
				name:'数据结构'
			},
			{
				id:3,
				name:'操作系统'
      },
      {
				id:4,
				name:'计算机组成原理'
			},
      {
				id:5,
				name:'计算机网络'
			}
    ],
  },

  onLoad: function () {
    this.getHomeIma();
    this.getBooks();
    
  },
  

  //------------------ 功能模块 start------------------
  getCartBook:function(){
    var userid =  getApp().globalData.userid;
    //console.log("userid:"+userid);
    var mark = 'getCartBook';
    wx.request({
      url: 'http://localhost:8080/youYanZaiXian/MallServlet',
      method: 'POST',
      data:{
        mark:mark,
        userid:userid,
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json'
      },
      success: (res)=>{
        var cartList = res.data.data.cartList;
        this.setData({
          cartList:cartList,
        })
        //console.log(this.data.cartList)
        this.processCartDate();  // 给cartList添加carshow属性
        this.calSumPrice();
        var cartAmount = cartList.length;
        //console.log("cartAmount:"+cartAmount);
        this.setData({
          cartAmount:cartAmount,
        });
      }
    });
  },

  // 计算购物车中的总价格
  calSumPrice:function(){
    var cartList = this.data.cartList;
    var sumPrice = 0;
    for(var i=0;i<cartList.length;i++){
      sumPrice = sumPrice+cartList[i].bookPrice;
    }
    //console.log("sumPrice:"+sumPrice);
    this.setData({
      sumPrice:sumPrice
    })
  },

  getBooks:function(){
    var mark = 'getBooks';
    wx.request({
      url: 'http://localhost:8080/youYanZaiXian/MallServlet',
      method: 'POST',
      data:{
        mark:mark,
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json'
      },
      success: (res)=>{
        var bList = res.data.data.bList;
        this.setData({
          bList:bList,
        })
        //console.log(this.data.bList)
        this.processDate();  // 由于异步而在此处调用
      }
    });
  },
  
  // 获取主页轮播图图片
  getHomeIma:function(){
    var mark = 'getHomeIma';
    wx.request({
      url: 'http://localhost:8080/youYanZaiXian/MallServlet',
      method: 'POST',
      data:{
        mark:mark,
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json'
      },
      success: (res)=>{
        var homeImaList = res.data.data.mhiList;
        this.setData({
          homeImageList:homeImaList,
        })
        //console.log(this.data.homeImageList)
      }
    });
  },

  // 给cartList添加carShow属性
  processCartDate:function(){
    var cartList = this.data.cartList;
    for(var i=0;i<cartList.length;i++){
      var key = "carShow";
      var value = true;
      cartList[i][key] = value;
    }
    this.setData({
      cartList:cartList,
    })
    //console.log(cartList);
  },


  // 将获得的book数据进行分类
  processDate:function(){
    var bList = this.data.bList;

    var bookList = [6];
    bookList[0] = new Array();
    bookList[0] = bList;
    for(var i=1;i<=5;i++){
      var count=0;
      bookList[i] = new Array();
      for(var j=0;j<bList.length;j++){
        if(bList[j].bookKind==i){
          bookList[i][count] = bList[j];
          count = count+1;
        }
      }
    }
    //console.log(bookList);
    this.setData({
      bookList:bookList,
    })
    this.getCartBook();
  },

  switchTab: function(e){  // 主页、分类、购物车之间的切换
    var idx = e.currentTarget.dataset.idx;
    this.setData({
      currentNavtab: idx
    });
    if(idx==0){
      // 切换到首页，重新获取数据
      this.getHomeIma();
      this.getBooks(); 
    }else if(idx==1){
      this.getBooks();
    }else if(idx==2){
      this.getCartBook();  // 不在onLoad中调用的原因是，app.js中还没获取完userid，mall.js的onLoad可能已经执行完了
    }
  },

  onTabItemTap(item) {  // 切换到“商城”，重新获取数据
    this.getHomeIma();
    this.getBooks(); 
    this.getCartBook();
  },

    selectNav(event) {
      let id = event.target.dataset.id,   // 侧边栏种类id:1-6,其作用主要是为了样式：选中侧边栏某个种类的样式变换
      index = parseInt(event.target.dataset.index);  // 用于调用对应书籍种类的数据，和bookList配合
      
      this.setData({
        curNav: id,   // 侧边栏种类id:1-6
        curIndex: index
      })
      //console.log("curNav:"+this.data.curNav)
      //console.log("curIndex:"+this.data.curIndex)
      
    },
carRemove: function(event){
  var that = this;
  var index = event.target.dataset.alphaBeta;
  var key = 'cartList['+index+'].carShow';
  var obj = {};
  obj[key] = false;
  this.setData(obj);

  var scid = event.currentTarget.dataset.scid;
  //console.log("scid:"+scid);
  var mark = 'carRemove';
    wx.request({
      url: 'http://localhost:8080/youYanZaiXian/MallServlet',
      method: 'POST',
      data:{
        mark:mark,
        scid:scid,
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json'
      },
      success: (res)=>{
        var suc = res.data.data.suc;
        if(suc==1){
          wx.showToast({
            title: '删除成功',
            icon: 'success',
            duration: 2000
          })
        }else{
          wx.showToast({
            title: '删除失败',
            icon: 'error',
            duration: 2000
          })
        }
        this.getCartBook();  // 删除后重新调用获取购物车数据
      }
    });
},
//-------------------- 功能模块 start----------------------------


// --------------------页面跳转、切换模块 start------------------------
goBookDetail:function(e){
  var book = e.currentTarget.dataset.book;
  var cartAmount = this.data.cartAmount;
  //console.log(book);
  var bookJson = JSON.stringify(book);
  wx.navigateTo({
    url: '../spdetail/spdetail?book='+bookJson+'&cartAmount='+cartAmount,
  })
},

toPay: function(){
  var cartList = this.data.cartList;
  var cartListJson = JSON.stringify(cartList);
  var sumPrice = this.data.sumPrice;
  //console.log("sumPrice:"+sumPrice);
  //console.log(cartList);
    wx.navigateTo({
      url: '../pay/pay?sumPrice='+sumPrice+'&cartList='+cartListJson,
    })
},
// --------------------页面跳转、切换模块 end------------------------


//根据标题搜索主页商品
getBook:function(e){
  var book=e.detail.value
  this.setData({book:book})
},

searchBook:function(){
  var book=this.data.book
  var mark='searchBook';
  wx.request({
    url: 'http://localhost:8080/youYanZaiXian/MallServlet',
    method:'POST',
    data:{
      mark:mark,
      book:book
    },
    header: {
      'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
      'Accept': 'application/json'
    },
    success: (res)=>{
      var bList = res.data.data.books;
      this.setData({
        bList:bList,
      })
      this.processDate();
    }
  })
},

//根据标题搜索购物车商品
getCommodity:function(e){
  var book=e.detail.value
  this.setData({book:book})
},

searchCommodity:function(){
  var book=this.data.book
  var mark='searchBook';
  wx.request({
    url: 'http://localhost:8080/youYanZaiXian/MallServlet',
    method:'POST',
    data:{
      mark:mark,
      book:book
    },
    header: {
      'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
      'Accept': 'application/json'
    },
    success: (res)=>{
      var bList = res.data.data.books;
      this.setData({
        bList:bList,
      })
      this.processDate();
    }
  })
}

});


/*
*      
*          ┌─┐       ┌─┐
*       ┌──┘ ┴───────┘ ┴──┐
*       │                 │
*       │       ───       │
*       │  ─┬┘       └┬─  │
*       │                 │
*       │       ─┴─       │
*       │                 │
*       └───┐         ┌───┘
*           │         │
*           │         │
*           │         │
*           │         └──────────────┐
*           │                        │
*           │                        ├─┐
*           │                        ┌─┘    
*           │                        │
*           └─┐  ┐  ┌───────┬──┐  ┌──┘         
*             │ ─┤ ─┤       │ ─┤ ─┤         
*             └──┴──┘       └──┴──┘ 
*                 神兽保佑 
*                 代码无BUG! 
*/
